﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class NetManager : Singleton<NetManager>
{
    public Queue<UnityWeb> webRequests = new Queue<UnityWeb>();

    public float currTime = 0f;
    private float delay = 0.1f;
    private int maxQueue = 3;
    private bool canNext = true;

    public Action OnNetManagerOK;

    private void Start()
    {
        OnNetManagerOK?.Invoke();
    }

    public void AddRequest(string url, Action<byte[]> action,bool now = false)
    {

        var req = new UnityWeb(url, action);
        if (now)
        {
            StartCoroutine(RequestWebData(req));
        }
        else
        {
            webRequests.Enqueue(req);
        }
    }

    private IEnumerator RequestWebData(UnityWeb web)
    {
        var webRequest = web.request;
        yield return webRequest.SendWebRequest();
        if (webRequest.error != null)
        {
            Debug.LogError("------------下载失败----------" + webRequest.error);
            Debug.LogError("-----------下载路径----------" + webRequest.url);
            this.AddRequest(web.url, web.action);
        }
        else
        {
            byte[] bytes = webRequest.downloadHandler.data;
            web.action?.Invoke(bytes);
        }

        webRequest.Dispose();
        canNext = true;
    }

    private void Update()
    {
        if (webRequests.Count == 0) return;
        if(canNext)
        {
            canNext = false;
            StartCoroutine(RequestWebData(webRequests.Dequeue())) ;
            currTime = Time.time;
        }
    }

}

public class UnityWeb
{
    public UnityWebRequest request;
    //public UnityWebRequest request;

    public int id;
    public string resName;
    public string url;
    public Action<byte[]> action;

    public UnityWeb(string url, Action<byte[]> action)
    {
        this.action = action;
        this.url = url;
        //request = new WWW(this.url);
        request = UnityWebRequest.Get(this.url);
    }

    public UnityWeb()
    {
    }

    public float GetDownloadProgress()
    {
        return 1;
    }
}